package com.medicine.hbp.http;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.http.HttpCallBack;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.medicine.hbp.dialog.Loading;
import com.medicine.hbp.sp.LoginSp;
import com.medicine.hbp.uitl.CommUtil;
import com.medicine.hbp.uitl.MyApplication;
import com.medicine.hbp.uitl.StartIntent;
import com.medicine.hbp.uitl.ToastUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

/**
 * 数据访问回调处理
 *
 * @author jindandan
 * @param <T>
 */
public abstract class LoginAppHttpCallBack<T> extends HttpCallBack {
	// Json字符串转对象错误
	private static final int ERROR_CODE_FROM_JSON_TO_OBJECT = -888;
	// Json字符串解析错误
	private static final int ERROR_CODE_JSON_PARSE = -777;

	private static final String STATUS = "status";
	private Class<T> classOfT; // 指定结果集泛型
	private Activity activity;
	private Loading appDialog = null;

	public LoginAppHttpCallBack(Class<T> classOfT, Activity activity) {
		this.classOfT = classOfT;
		this.activity = activity;
		appDialog = new Loading(activity);
		appDialog.showDialog();
	}

	public LoginAppHttpCallBack(Class<T> classOfT) {
		this.classOfT = classOfT;
	}

	/**
	 * 访问成功回调
	 *
	 * @param result
	 *            //解析成功对象
	 */
	public abstract void onSuccess(T result);

	/**
	 * 失败回调
	 */
	public abstract void onFailures(int errorCode, String errorMsg);
	@Override
	public void onFailure(int errorNo, String strMsg) {
		super.onFailure(errorNo, strMsg);
		String msg;
		if(strMsg.equals("NoConnection error")){
			msg="无网络";
		}else if(strMsg.equals("java.net.SocketTimeoutException: socket timeout")){
			msg="网络链接超时！";
		}else{
			msg=strMsg;
		}
		onFailures(errorNo, msg);
	}

	//	@Override
//	public void onSuccess(Map<String, String> headers, byte[] t) {
//		super.onSuccess(headers, t);
//		if(TextUtils.isEmpty(MyApplication.getMyApplication().getCookitString())&&!TextUtils.isEmpty(headers.get("Set-Cookie"))){
//			MyApplication.getMyApplication().setCookitString(headers.get("Set-Cookie"));
//		}
//	}
	@Override
	public void onSuccess(String t) {
		super.onSuccess(t);
		Gson gson = new Gson();
		if(CommUtil.isLog){
			Log.e("TAG", t);
		}
		try {
			JSONObject jsonObject = new JSONObject(t);
			if (jsonObject.getString(STATUS).equals("000000")) {// 访问成功
				T result = null;
				LoginSp.setToken(jsonObject.getString("token"), activity);
				try {
					result = gson.fromJson(t, classOfT);
				} catch (JsonSyntaxException e) {
					onFailure(ERROR_CODE_FROM_JSON_TO_OBJECT, "Json字符串转对象错误");
					return;
				}
				if (result != null) {
					onSuccess(result);
				}
			}
//			else if (jsonObject.getString(STATUS).equals("000033")) {
//				StartIntent.MainStartLogin(activity,0);
//			}
			else {
				onFailure(Integer.valueOf(jsonObject.getString("status")),
						jsonObject.getString("message"));
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
			onFailure(ERROR_CODE_JSON_PARSE, "Json字符串解析错误");
		}
	}

	@Override
	public void onFinish() {
		super.onFinish();
		if (appDialog != null) {
			appDialog.dismissDialog();
		}

	}

	class AppDialog {
		private ProgressDialog progressDialog;
		public AppDialog() {
			OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
				public boolean onKey(DialogInterface dialog, int keyCode,
									 KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK
							&& event.getRepeatCount() == 0) {
						return true;
					} else {
						return false;
					}
				}
			};
			// this表示该对话框是针对当前Activity的
			progressDialog = new ProgressDialog(activity);
			// 设置进度条风格STYLE_SPINNER
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("拉取数据中......");
			progressDialog.setOnKeyListener(keylistener);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.onStart();
		}

		public void showDialog() {
			progressDialog.show();
		}

		public void dismissDialog() {
			progressDialog.dismiss();
		}
	}
}
